package com.x.Part2_Exception类.Throw;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * ClassName: Test
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.03.18 15:52
 */
public class Test1 {
    public static void main(String[] args) {

    }

    @Test
    public void test1() {
        try {
            Scanner scanner = new Scanner(System.in);
            int i = scanner.nextInt();
            System.out.println(i);

        } catch (InputMismatchException | NullPointerException e) {
            e.printStackTrace();
        }
        System.out.println("程序继续执行至结束");

    }


    @Test
    //FileNotFoundException
    //IOException
    public void test2() throws IOException, FileNotFoundException {//预处理，不处理编译不让过

        try {
            File file = new File("D:/My code/1111.txt");
            FileInputStream fis = new FileInputStream(file);//可能出现java.io.FileNotFoundException
            int data = fis.read();//可能出现java.io.IOException
            while(data !=-1){
                System.out.print((char)data);
                data = fis.read();//可能出现java.io.IOException
            }
            fis.close();//可能出现java.io.IOException
        } catch (FileNotFoundException  e) {
            System.out.println(e.getMessage());
            //System.out.println(10/0);
        } catch (IOException e){//FileNotFoundException是IOException的子类，顺序不能颠倒
            System.out.println(e.getMessage());
        }finally {
            System.out.println("这里的代码就算catch中有异常也会被执行");
        }

        System.out.println("如果catch有异常，外面的代码不会执行");

    }


    @Test
    //FileNotFoundException
    //IOException
    public void test3() {//预处理，不处理编译不让过
        FileInputStream fis =null;
        try {
            File file = new File("D:/My code/111.txt");
            fis = new FileInputStream(file);//如果此行出异常，fis=null，fis.close()时要判断是否为mull
            int data = fis.read();
            while(data !=-1){
                System.out.print((char)data);
                data = fis.read();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());

        } finally {
            try {
                if(fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }
}
